<template>
  <div class="app-container">
    <div class="class-table">
      <!-- 下拉选择学期 -->
      <el-select
        class="semester-select"
        v-model="semesterId"
        placeholder="请选择学期"
        @change="changeSemester"
      >
        <el-option
          v-for="(item, index) in semesterData"
          :key="index"
          :value="item.id"
          :label="item.semesterName"
        ></el-option>
      </el-select>
      <!-- 下拉选择班级 -->
      <el-select
        class="class-select"
        @change="handleSelectChange"
        @clear="clearListener"
        clearable
        v-model="roomNo"
        placeholder="请选择教室"
      >
        <el-option
          v-for="(item, index) in roomData"
          :key="index"
          :value="item.roomNo"
          :label="item.roomName"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="exportExcel">导出课表</el-button>
    </div>
    <br />
    <el-table
      :data="classTableData.lessons"
      border
      style="width: 100%"
      id="my-table"
    >
      <!-- 时间列 -->
      <el-table-column prop="name" label="时间" width="180">
        <template slot-scope="scope">
          <p>{{ "第" + digital2Chinese(scope.$index + 1) + "节" }}</p>
          <p class="period">{{ scope.row }}</p>
        </template>
      </el-table-column>

      <!-- 周次和课程信息列 -->
      <el-table-column
        v-for="(weekNum, weekIndex) in classTableData.courses"
        :key="weekIndex"
        :label="'周' + digital2Chinese(weekIndex + 1, 'week')"
        width="180"
      >
        <template slot-scope="scope">
          <div
            class="course-info"
            v-html="
              classTableData.courses[weekIndex][scope.$index]
            "
          ></div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        2: "success",
        0: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      classTimeTableData: [],
      roomData: [],
      semesterData: [],
      roomNo: "",
      semesterId: "",
      list: null,
      listLoading: true,
      search: "",
      total: 0,
      currentPage: 1,
      currentIndex: "",
      pagesize: 10,
      classTableData: {
        lessons: [
          "08.20-09.55",
          "10.15-11.50",
          "14.20-15.55",
          "16.15-17.50",
          "18.30-20.05",
        ],
        courses: [[], [], [], [], [], [], []],
      },
    };
  },
  created() {
    this.getList();
    this.getRoomNo();
    this.getSemester();
  },
  mounted() {
    // 先create后mouted
    let id = this.$store.getters.getSemesterId;
    this.semesterId = id;
  },
  methods: {
    changeSemester() {
      this.clearListener()
      this.getList();
    },
    getClassPart(courseString) {
      if (!courseString) return "-";
      // 假设 courseString 格式为 "班级-课程名"，例如 "2班-明理"
      const [className, courseName, roomName] = courseString.split("-");
      // 使用 HTML 换行标签 <br> 来实现换行
      return `${className}<br>${courseName}<br>${roomName}`;
    },
    initClassTableData() {
      this.classTableData = {
        lessons: [
          "08.20-09.55",
          "10.15-11.50",
          "14.20-15.55",
          "16.15-17.50",
          "18.30-20.05",
        ],
        courses: [[], [], [], [], [], [], []],
        timetableId: [[], [], [], [], [], [], []],
        timeslot: [[], [], [], [], [], [], []],
      };
      return true;
    },
    setToTable(ret) {
      if (!this.initClassTableData()) {
        // console.log('initClassTableData失败', this.classTableData)
        return;
      } else {
        // console.log('initClassTableData成功',this.classTableData)
      }

      let level = 0;
      let times = 0;
      let index = 0;
      let beforeTimeslot = -1;
      let flag = false; // flag为true表示 全空
      let sameTimeslotIndex = 0;
      if (this.roomNo == "") {
        flag = true;
      }
      if (this.semesterId == null) {
        flag = true;
      }
      for (let timess = 0; timess < 35; timess++) {
        const item = ret[index];
        if (!flag && item != undefined && beforeTimeslot == item.timeslot) {
          timess--;
        }
        level = Math.floor(timess / 5);
        if (flag || index >= ret.length || parseInt(item.timeslot) != timess) {
          // 添加空字符串表示没有课程
          this.classTableData.courses[level].push("");
          this.classTableData.timetableId[level].push(-1);
          this.classTableData.timeslot[level].push(timess);
          index = index - 1;
        } else {
          let section =
            "(" +
            ((item.timeslot % 5) * 2 + 1) +
            "-" +
            ((item.timeslot % 5) * 2 + 2) +
            "节)";
          let biweekly =
            item.biweekly == 1 ? "(单)" : item.biweekly == 2 ? "(双)" : "";
          let time =
            section + item.startWeek + "-" + item.endWeek + "周" + biweekly;
          let className = item.className;
          let teacherName = item.teacherName;
          let course = item.courseNo + "-" + item.courseName;
          let size = item.size;

          let msg =
            time +
            "/" +
            className +
            "/" +
            teacherName +
            "/" +
            course +
            "/" +
            "选课人数：" +
            size;

          if (beforeTimeslot != item.timeslot) {
            sameTimeslotIndex = 0;

            this.classTableData.courses[level].push(msg);
            this.classTableData.timetableId[level][item.timeslot % 5] = item.id;
            this.classTableData.timeslot[level].push(item.timeslot);
          } else {
            sameTimeslotIndex++;
            let oldmsg = this.classTableData.courses[level][item.timeslot % 5];
            this.classTableData.courses[level][item.timeslot % 5] =
              oldmsg + "<br/>" + msg;
            let oldid =
              this.classTableData.timetableId[level][item.timeslot % 5];
            this.classTableData.timetableId[level][item.timeslot % 5] =
              oldid + "@@@" + item.id;
            this.classTableData.timeslot[level].push(item.timeslot);
          }

          beforeTimeslot = item.timeslot;
        }
        times = times + 1;
        index++;
      }

      if (ret.length == 0) {
        this.$message({ message: "暂无课表", type: "success" });
      }
      console.log(this.classTableData);
    },
    // 查询全部课程表
    getList() {
      this.listLoading = true;
      this.classTableData.courses.forEach((item, index) => {
        item.length = 0; // 直接将数组长度设置为0来清空数组
      });
      this.$axios
        .get("/timetable/getList", {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          let ret = res.data.data;
          this.classTimeTableData = ret.records;
          this.setToTable(ret)
          this.listLoading = false;
        })
        .catch((error) => {
          this.$message.error("查询课程表失败");
        });
    },
    // 根据学期和教室查询课表
    queryClass() {
      this.listLoading = true;
      this.classTableData.courses.forEach((item, index) => {
        item.length = 0; // 直接将数组长度设置为0来清空数组
      });
      this.$axios
        .get("http://localhost:8081/timetable/room/"+ this.semesterId + "/" + this.roomNo)
        .then((res) => {
          console.log(res);
          let ret = res.data.data;
          this.setToTable(ret)
          this.listLoading = false;
        })
        .catch((error) => {
          console.log("查询课表失败");
        });
    },
    //获得教室列表
    getRoomNo() {
      this.listLoading = true;
      this.$axios
        .get("http://localhost:8081/room/getList")
        .then((res) => {
          let ret = res.data.data;
          for (let index = 0; index < ret.length; index++) {
            const item = ret[index];
            this.roomData[index] = item;
          }
        })
        .catch((error) => {
          console.log("查询班级失败");
        });
    },
    //获得学期列表
    getSemester() {
      this.listLoading = true;
      this.$axios
        .get("http://localhost:8081/semester/getList")
        .then((res) => {
          let ret = res.data.data;
          // this.semesterData = ret;
          for (let index = 0; index < ret.length; index++) {
            const item = ret[index];
            this.semesterData[index] = item;
          }
        })
        .catch((error) => {
          console.log("查询学期失败");
        });
    },
    exportExcel() {
      // 1.生成Excel工作簿对象
      const ws = XLSX.utils.table_to_sheet(document.getElementById("my-table"));
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
     
      // 设置列宽
      const defaultColWidth = 20; // 字符宽度
      const range = XLSX.utils.decode_range(ws["!ref"]);
      for (let C = range.s.c; C <= range.e.c; ++C) {
        if (!ws["!cols"]) ws["!cols"] = [];
        ws["!cols"][C] = { width: defaultColWidth };
      }
      // 假设我们设置前10行的行高为20px（这里仅作为示例）
      // 在实际应用中，你可能需要基于 ws 的实际行数来动态设置行高
      const defaultRowHeight = 100; // 像素高度
      // 设置第一行行高为20
      if (!ws["!rows"]) ws["!rows"] = [];
      ws["!rows"][0] = { hpx: 20 }; // 第一行的行高设置为20像素

      // 设置2-6行的行高为50
      for (
        let R = 1;
        R <= 6 && ws[XLSX.utils.encode_cell({ r: R, c: 0 })];
        ++R
      ) {
        ws["!rows"][R] = { hpx: defaultRowHeight }; // 2-6行的行高设置为50像素
      }
      // 生成Excel文件并使用blob类型保存
      const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
      const blob = new Blob([wbout], { type: "application/octet-stream" });
      saveAs(blob, "课表.xlsx");
    },
    /**
     * 数字转中文
     * @param {Number} num 需要转换的数字
     * @param {String} identifier 标识符
     * @returns {String} 转换后的中文
     */
    digital2Chinese(num, identifier) {
      const character = [
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        // "七",
        // "八",
      ];
      return identifier === "week" && (num === 0 || num === 7)
        ? "日"
        : character[num];
    },
    // 清除班级和学期
    clearListener() {
      this.roomNo = "";
    },
    // 得到对应选中的班级
    handleSelectChange(val) {
      // 这里的val就是选择的班级了
      this.roomNo = val;
      this.queryClass();
    },
    handleSizeChange(val) {
      this.pagesize = val;
      console.log(`每页 ${val} 条`);
    },
  },
};
</script>
<style scoped>
.course-info {
  white-space: pre-wrap; /* 保留空白和换行 */
}
.class-select {
  padding-left: 30px;
  padding-right: 30px;
}
</style>